import { EStorageKey } from '@/types/enums'
import { consoleWarn } from './logger'

function getStorageData(key: EStorageKey, parse?: boolean): string | null
function getStorageData<T>(key: EStorageKey, parse?: boolean): T | null
function getStorageData(key: EStorageKey, parse?: boolean): any {
  const value = window.localStorage.getItem(key)
  if (parse && value) {
    try {
      const result = JSON.parse(value)
      return result
    } catch (e) {
      consoleWarn('appStorage.get failed, err:', e)
      return null
    }
  } else {
    return value
  }
}

function clearStorageData(key: EStorageKey | EStorageKey[]) {
  let keyList: EStorageKey[] = []
  if (Array.isArray(key)) {
    keyList = key
  } else {
    keyList = [key]
  }
  keyList.forEach((item) => {
    window.localStorage.removeItem(item)
  })
}

const appStorage = {
  save(key: EStorageKey, value: string) {
    window.localStorage.setItem(key, value)
  },
  get: getStorageData,

  clear: clearStorageData
}

export default appStorage

/**
 * window.localStorage => 浏览器永久存储，用于长久保存整个网站的数据，保存的数据没有过期时间，直到手动去删除。
 */
// TODO 这里应该使用sessionStorage，因为localStorage在关闭浏览器后数据一直存在，导致数据不一致
export const localStorage = {
  set(key: string, val: any) {
    window.sessionStorage.setItem(key, JSON.stringify(val))
  },
  get(key: string) {
    let json: any = window.sessionStorage.getItem(key)
    if (json !== null) {
      try {
        json = JSON.parse(json)
      } catch (e) {
        json = json as any
      }
    } else {
      json = null
    }

    return json
  },
  remove(key: string) {
    window.sessionStorage.removeItem(key)
  },
  clear() {
    window.sessionStorage.clear()
  }
}

/**
 * window.sessionStorage => 浏览器本地存储，数据保存在当前会话中，在关闭窗口或标签页之后将会删除这些数据。
 */
export const sessionStorage = {
  set(key: string, val: any) {
    window.sessionStorage.setItem(key, JSON.stringify(val))
  },
  get(key: string) {
    const json: any = window.sessionStorage.getItem(key)
    return JSON.parse(json)
  },
  remove(key: string) {
    window.sessionStorage.removeItem(key)
  },
  clear() {
    window.sessionStorage.clear()
  }
}
